/**
 * 15-600: Java and J2EE
 * Instructor: Jeff Eppinger
 * Done By:	Mohammad al Khani
 * Date Dec 10, 2011
 */

package controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import model.BookmarkDAO;
import model.Model;

import org.mybeans.form.FormBeanFactory;

import dataBeans.User;
import formBean.DeleteBookmarkForm;

public class DeleteBookmarkAction extends Action{
	private FormBeanFactory<DeleteBookmarkForm> formBeanFactory = FormBeanFactory.getInstance(DeleteBookmarkForm.class);
	private BookmarkDAO bookmarkDAO;
	public DeleteBookmarkAction(Model model){
		bookmarkDAO = model.getBookmarkDAO();
	}
	
	public String getName(){ 
		return "deleteBookmark.do"; 
	}
    
    public String perform(HttpServletRequest request) {
    	String webapp = request.getContextPath();
    	List<String> errors = new ArrayList<String>();
    	request.setAttribute("errors",errors);

    	try {
    		DeleteBookmarkForm form = formBeanFactory.create(request);
    		request.setAttribute("deleteForm",form);

    		if (!form.isPresent()) {
    			return "manage.do";
    		}
    		
    		errors.addAll(form.getValidationErrors());
    		if (errors.size() != 0) {
    			return "manage.do";
    		}
    		
    		if(request.getSession().getAttribute("user") != null){
    			bookmarkDAO.deleteBookmark(form.getUrl(), ((User)request.getSession().getAttribute("user")).getUserId());
    			return webapp + "/manage.do";
    		}else{
    			return webapp + "/authorizationError.jsp";
    		}
    	}catch(Exception e){
    		e.printStackTrace();
    		return "error.jsp";
    	}
    }

}
